import { FindAllOrderDto } from './dto/findAll-order.dto';
import { Injectable } from '@nestjs/common';
import { CreateOrderDto } from './dto/create-order.dto';
import { UpdateOrderDto } from './dto/update-order.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Order } from './order.entity';
import { Repository } from 'typeorm';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
  ) {}

  create(createOrderDto: CreateOrderDto) {
    const entity = this.orderRepository.create(createOrderDto);
    return this.orderRepository.save(entity);
  }

  async findAll(findAllOrderDto: FindAllOrderDto) {
    const { limit, page, ...params } = findAllOrderDto;
    const result = await this.orderRepository.findAndCount({
      where: params,
      skip: (page - 1) * limit,
      take: limit,
    });
    return {
      list: result[0],
      total: result[1],
    };
  }

  findOne(id: number) {
    return this.orderRepository.findOneById(id);
  }

  async update(id: number, updateOrderDto: UpdateOrderDto) {
    const hasEntriy = await this.orderRepository.findOneById(id);
    if (!hasEntriy) {
      return;
    }
    const updateInfo = this.orderRepository.merge(hasEntriy, updateOrderDto);
    const result = await this.orderRepository.save(updateInfo);
    return result;
  }

  async remove(id: number) {
    const result = await this.orderRepository.delete(id);
    return result;
  }

  async getTotal() {
    const result = await this.orderRepository.count();
    const stateList = await Promise.all([
      this.orderRepository.countBy({ state: 0 }),
      this.orderRepository.countBy({ state: 1 }),
      this.orderRepository.countBy({ state: 2 }),
    ]);

    return {
      total: result,
      state: [
        {
          type: '交易取消',
          value: stateList[0],
        },
        {
          type: '待付款',
          value: stateList[1],
        },
        {
          type: '交易完成',
          value: stateList[2],
        },
      ],
    };
  }
}
